package com.sservice.web.controller.admin;

import com.sservice.common.Arith;
import com.sservice.common.CompareObject;
import com.sservice.common.Constants;
import com.sservice.common.SameUrlData;
import com.sservice.model.dao.OfferNumLogMapper;
import com.sservice.model.vo.GoodsVo;
import com.sservice.model.vo.OfferVo;
import com.sservice.urp.entity.Role;
import com.sservice.urp.vo.UserVo;
import com.sservice.service.service.*;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.model.entity.*;
import com.sservice.web.log.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/offer")
public class OfferController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IOfferService depService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private OfferNumLogMapper onlDao;
    @Autowired
    private IOfferPriceLogService oplDao;
    @Autowired
    private IGoodsPriceIndexService ogpiDao;
    @Autowired
    private ISysLogService sysLogService;

    /**
     * 创建
     *
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> create(Offer arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(arg.getGoodsId()));
        arg.setCode(goods.getCode());
        arg.setGoodsName(goods.getName());
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        BaseResult<Object> res = null;


        Boolean isManger = false;
        for (Role role : user.getRoles()) {
            if (String.valueOf(role.getId()).equals(Constants.SUPER_MANAGER_ROLE_ID)) { /// 超级管理员账户判断
                isManger = true;
            }
        }
        if (!isManger) {
            String str = goods.getOperatorId();
            if (str != null) {
                boolean isOperator = false;
                String[] operatId = str.split(",");
                for (int i = 0; i < operatId.length; i++) {
                    if ((operatId[i].equals(String.valueOf(user.getId())))) {
                        isOperator = true;
                        break;
                    }
                }
                if (!isOperator) {
                    return new BaseResult(false, "非运营人员或超级管理员用户，不能发布报价", 403);
                }
            } else {
                return new BaseResult(false, "非运营人员或超级管理员用户，不能发布报价", 403);
            }

        }
//        if(str!=null)
        arg.setGoodsName(goods.getName());
        arg.setCreatorId(String.valueOf(user.getId()));
        arg.setCreator(user.getUserName());
//        arg.setPrice(arg.getActualPrice().doubleValue());//
        int service_res = depService.insertSelective(arg);
        if (service_res > 0) {
            sysLogService.log("创建", request, Integer.valueOf(arg.getId()), Action.offerType);
        }
        res = new BaseResult(true, service_res);
        return res;
    }

    /***
     * 增加可售数量
     * @param arg
     * @param session
     * @param request
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/plus", method = RequestMethod.POST)
    public BaseResult<Object> plus(Offer arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

        Offer offer = depService.selectByPrimaryKey(Integer.valueOf(arg.getId()));
        Double number = arg.getSaleNum();
        UserVo user = (UserVo) session.getAttribute(Constants.USER);


        arg.setSaleNum(Arith.add(arg.getSaleNum(), offer.getSaleNum()));
        int service_res = depService.updateByPrimaryKeySelective(arg);
        if (service_res > 0) { // 记录操作日志
            OfferNumLog onl = new OfferNumLog();
            onl.setNumber(number);
            onl.setUserId(String.valueOf(user.getId()));
            onl.setOfferId(arg.getId().toString());
            onlDao.insertSelective(onl);
            sysLogService.log("增加报价数量" + arg.getSaleNum(), request, Integer.valueOf(arg.getId()), Action.offerType);
        }

        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete(Offer arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        arg.setStatus("3"); //逻辑删除
        Order order = new Order();
        order.setOfferId(arg.getId().toString());
        int re = orderService.queryCountBeforeDelete(order);
        if (re > 0) {
            return new BaseResult(false, "该报价数据关联订单数据，无法删除!", 403);
        }
        int service_res = depService.updateByPrimaryKeySelective(arg);
        if (service_res > 0) {
            sysLogService.log("删除", request, Integer.valueOf(arg.getId()), Action.offerType);
        }
        return new BaseResult(true, service_res);
    }

    /**
     * 通过订单ID
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getByOrderId", method = RequestMethod.GET)
    public BaseResult<Object> getByOrderId(Order arg) {
        Order service_res = orderService.selectByPrimaryKey(arg.getId());
        Offer offer = depService.selectByPrimaryKey(Integer.valueOf(service_res.getOfferId()));
        return new BaseResult(true, offer);
    }
//

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Offer arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        if (arg.getPrice() != null) {
            Offer ofer = depService.selectByPrimaryKey(arg.getId());
            if (!ofer.getPrice().equals(arg.getPrice())) {
                arg.setUpdatePriceTime(new Timestamp(System.currentTimeMillis()));
                int r = oplDao.insertLog(String.valueOf(user.getId()), arg.getPrice(), arg.getId().toString());
                if (r > 0) {
                    ogpiDao.updateAvgByGoodsId(Integer.valueOf(ofer.getGoodsId()));
                }
            }
        }
        Offer offer = depService.selectByPrimaryKey(arg.getId());
        int service_res = depService.updateByPrimaryKeySelective(arg);
        if (service_res > 0) {
            Map<String, Object> res = CompareObject.contrastObj(arg, offer);
            sysLogService.log(res, request, Integer.valueOf(arg.getId()), Action.offerType);
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(OfferVo arg, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        for (Role role : user.getRoles()) {
            if (String.valueOf(role.getId()).equals(Constants.SUPER_MANAGER_ROLE_ID)) { /// 超级管理员账户判断
                isManger = true;
            }
        }
        if (!isManger) { //运营账户判断判断
            GoodsVo goods = new GoodsVo();
            List<Goods> list = goodsService.queryGoodsCategory(goods);
            List<String> lstr = new ArrayList<String>();
            for (Goods item : list) {
                if (("," + item.getOperatorId() + ",").indexOf("," + user.getId() + ",") > -1) {
                    lstr.add(String.valueOf(item.getId()));
                }
            }
            if (lstr.size() > 0) {
                arg.setList(lstr);
            }
        }
        if (!isManger && null == arg.getList()) {
            return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
        }

        List<OfferVo> list = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


}
